import { forwardRef, useImperativeHandle } from 'react';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import ErrorOutlinedIcon from '@mui/icons-material/ErrorOutlined';
import { useControlledState } from '@/hooks';

export type IAlertDialogProps = {
  open?: boolean;
  onOpenChange?: (open?: boolean) => void;
  title?: React.ReactNode;
  content?: React.ReactNode;
  onConfirm?: () => void;
};

export type IAlertDialogRef = {
  setOpen: (open?: boolean) => void;
};

export const AlertDialog = forwardRef<IAlertDialogRef, IAlertDialogProps>((props, ref) => {
  const { title, content, onConfirm } = props;
  const [open, setOpen] = useControlledState(props.open, props.onOpenChange);

  const handleClose = () => {
    setOpen(false);
  };

  const handleOk = () => {
    setOpen(false);
    onConfirm?.();
  };

  useImperativeHandle(ref, () => ({
    setOpen,
  }));

  return (
    <Dialog
      sx={{ '.MuiTypography-root': { display: 'flex', alignItems: 'center', gap: '4px' }, '.MuiPaper-root': { minWidth: 400 } }}
      open={!!open}
      onClose={handleClose}
    >
      <DialogTitle>
        <ErrorOutlinedIcon color="warning" />
        {title}
      </DialogTitle>
      {!!content && (
        <DialogContent>
          <DialogContentText>{content}</DialogContentText>
        </DialogContent>
      )}
      <DialogActions>
        <Button onClick={handleClose}>取消</Button>
        <Button onClick={handleOk} autoFocus>
          确定
        </Button>
      </DialogActions>
    </Dialog>
  );
});
